export let util = {
  debounce(func, wait = 500, immediate = false) {
    // 清除定时器
    if (this.debounceTimeout !== null) clearTimeout(this.debounceTimeout)
    // 立即执行，此类情况一般用不到
    if (immediate) {
      const callNow = !this.debounceTimeout
      this.debounceTimeout = setTimeout(() => {
        this.debounceTimeout = null
      }, wait)
      if (callNow) typeof func === 'function' && func()
    } else {
      // 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
      this.debounceTimeout = setTimeout(() => {
        typeof func === 'function' && func()
      }, wait)
    }
  },
  throttle(func, wait = 500, immediate = true) {
    if (immediate) {
      if (!this.throttleFlag) {
        this.throttleFlag = true
        // 如果是立即执行，则在wait毫秒内开始时执行
        typeof func === 'function' && func()
        this.throttleTimer = setTimeout(() => {
          this.throttleFlag = false
        }, wait)
      }
    } else if (!this.throttleFlag) {
      this.throttleFlag = true
      // 如果是非立即执行，则在wait毫秒内的结束处执行
      this.throttleTimer = setTimeout(() => {
        this.throttleFlag = false
        typeof func === 'function' && func()
      }, wait)
    }
  }
}

export default function ($x, {
  utilExtend
} = {}, app) {
  Object.assign(util, utilExtend || {})
  $x.util = util
}